//
//  DBResponder.m
//  Voice2AlarmNote
//
//  Created by onemade on 14-10-28.
//  Copyright (c) 2014年 CNPC. All rights reserved.
//

#import "DBResponder.h"

@implementation DBResponder

//设置数据库路径
-(NSURL *)applicationDocumentDictionary
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    //    [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


//初始化实体
-(NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return  _managedObjectModel;
    }
    
    //    return _managedObjectModel =[NSManagedObjectModel mergedModelFromBundles:nil];
    
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:self.tableName withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

//初始化数据库
-(NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return  _persistentStoreCoordinator;
    }
    NSURL *store = [[self applicationDocumentDictionary] URLByAppendingPathComponent:self.DBName];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:store options:nil error:&error]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"错误" message:[NSString stringWithFormat:@"%@ \n %@",error,[error userInfo]] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    
    return _persistentStoreCoordinator;
}

//初始化实体上下文
-(NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return  _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

//保存更改
-(void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *context  = [self managedObjectContext];
    if (context != nil) {
        if ([context hasChanges] && ![context save:&error]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存失败" message:[NSString stringWithFormat:@"%@",error] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            abort();
        }
    }
}

@end
